package com.aidex.biz.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import com.aidex.biz.domain.AccountInfo;
import com.aidex.biz.domain.AccountType;
import com.aidex.biz.domain.UserInfo;
import com.aidex.biz.service.*;
import com.aidex.common.utils.StringUtils;
import com.aidex.common.utils.http.HttpUtils;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 小程序用户信息Service业务层处理
 *
 * @author sean
 * @email 2074844820@qq.com
 * @date 2022-09-21
 */
@Service

public class WeChatLoginServiceImpl implements WeChatLoginService {
    private static final Logger log = LoggerFactory.getLogger(WeChatLoginServiceImpl.class);

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private AccountTypeService accountTypeService;
    @Autowired
    private AccountInfoService accountInfoService;
    @Autowired
    private LbsMapService lbsMapService;


    String appId = "";
    String appSecret = "";


    @Override
    public void setAppId(String appId, String appSecret) {
        this.appId = appId;
        this.appSecret = appSecret;
    }

    /**
     * 授权操作获取token
     *
     * @return
     */
    public String getAccessToken() {

        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret"
                + "=" + appSecret;
        String json = HttpUtils.doGet(url);
        // 字符串转化为json对象
        JSONObject jsonObject = JSONObject.parseObject(json);
        // 根据key值拿到value
        return jsonObject.getString("access_token");
    }

    @Override
    public JSONObject getOpenId(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + appSecret + 
                "&js_code=" + code + "&grant_type=authorization_code";
        String res = HttpUtils.doGet(url);
        return JSONObject.parseObject(res);
    }

    @Override
    public String getphoneNumber(String code) {
        String phoneNumber="";
        String accessToken = this.getAccessToken();
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken;
        JSONObject object = new JSONObject();
        object.put("code", code);
        String res = HttpUtils.doPost(url, object);
        if("0".equals(JSONObject.parseObject(res).getString("errcode"))){
             phoneNumber = JSONObject.parseObject(res).getJSONObject("phone_info").getString("phoneNumber");
        }
        return phoneNumber;
    }

    @Override
    public UserInfo login(UserInfo userInfo) {
        UserInfo user = userInfoService.get(userInfo.getOpenid());
        // 先转换坐标
        Map<String, String> map=new HashMap<>();
        if(null!=userInfo.getLat()){
            map= lbsMapService.getCityInfoByLatLng(userInfo.getLat(), userInfo.getLng());
        }
        if (null == user) {
            user = new UserInfo();
            user.setOpenid(userInfo.getOpenid());
            user.setId(userInfo.getOpenid());
            user.setCompanyId(userInfo.getCompanyId());
            user.setIsNewRecord();
            user.setIsShiming(0);
            user.setArea(map.get("area"));
            user.setProvince(map.get("province"));
            user.setCity(map.get("city"));
            user.setStreet(map.get("street"));
            user.setStreetNumber(map.get("streetNumber"));
            user.setCrossroad(map.get("crossroad"));
            user.setTuijianUser(userInfo.getTuijianUser());
            user.setStatus("0");
            user.setType("0");
            return register(user);
        } else {
            if (StringUtils.isEmpty(user.getTuijianUser())) {
                user.setTuijianUser(userInfo.getTuijianUser());
            }
            user.setArea(map.get("area"));
            user.setProvince(map.get("province"));
            user.setCity(map.get("city"));
            user.setStreet(map.get("street"));
            user.setStreetNumber(map.get("streetNumber"));
            user.setCrossroad(map.get("crossroad"));
            userInfoService.save(user);
        }
        return user;
    }

    @Override
    public UserInfo register(UserInfo userInfo) {
        if (userInfoService.save(userInfo)) {
            // 同步到商城
            //boolean isok = userInfoService.toShopAddUser(userInfo);
//            if (!isok) {
//                log.error("创建商城用户失败！");
//            }
            // 创建账户
            List<AccountType> accountTypeList = accountTypeService.findList(new AccountType());
            AccountInfo accountInfo = new AccountInfo();
            accountInfo.setUserInfoId(userInfo.getId());
            if (accountInfoService.findList(accountInfo).size() > 0) {
                return userInfo;
            }
            int sort = 10;
            for (AccountType accountType : accountTypeList) {
                accountInfo = new AccountInfo();
                accountInfo.setStatus("0");
                accountInfo.setUserInfoId(userInfo.getId());
                accountInfo.setAccountId(accountType.getId());
                accountInfo.setAccount(new BigDecimal(0.00));
                accountInfo.setSort(sort);
                accountInfo.setCompanyId(userInfo.getCompanyId());
                accountInfoService.save(accountInfo);
                sort += 10;
            }
            return userInfo;
        }
        return null;
    }

    @Override
    public String getScheme(String url, String query) {
        WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();

        config.setAppid(this.appId);
        config.setAccessToken(this.getAccessToken());
        config.setSecret(this.appSecret);
        config.setMsgDataFormat("JSON");
        WxMaService wxMaService = new WxMaServiceImpl();
        wxMaService.setWxMaConfig(config);
        byte[] data = null;
        try {

            File file = wxMaService.getQrcodeService().createWxaCode(url + query);
            InputStream in = new FileInputStream(file);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Base64.Encoder encoder = Base64.getEncoder();
        return encoder.encodeToString(data);

    }


    /**
     * 该接口用于获取小程序码，适用于需要的码数量极多的业务场景。通过该接口生成的小程序码，永久有效，数量暂无限制
     * @param scene
     * @param url
     * @return
     */
    public String getUnlimitedQRCode(String scene, String url){
        WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
        config.setAppid(this.appId);
        config.setAccessToken(this.getAccessToken());
        config.setSecret(this.appSecret);
        config.setMsgDataFormat("JSON");
        WxMaService wxMaService = new WxMaServiceImpl();

        wxMaService.setWxMaConfig(config);
        byte[] data = null;
        try {
            File file = wxMaService.getQrcodeService().createWxaCodeUnlimit(scene,url);
            InputStream in = new FileInputStream(file);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Base64.Encoder encoder = Base64.getEncoder();
        return encoder.encodeToString(data);

    }

    /**
     * h5 登录用户授权链接
     * @param appid 公众号APPID
     * @param scope 授权作用域 snsapi_base（只能拿openid）和snsapi_userinfo(昵称、性别)
     * @param redirectUri 授权后重定向的回调链接地址
     */
    @Override
    public String getWxH5Auth2(String appid, String scope, String redirectUri,String state) {
        String url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI" +
                "&response_type=code&scope=SCOPE&state=STATE#wechat_redirect";
        url=url.replace("APPID",appid).replace("SCOPE",scope).replace("REDIRECT_URI",redirectUri).replace("STATE",
                state);
        return url;
    }

    /**
     * 公众号h5登录获取token
     * @param appid 公众号APPID
     * @param secret 公众号的appsecret
     * @param code 获取的code参数
     *
     */
    public String getMpH5AccessToken(String appid,String secret,String code){
        String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
        url=url.replace("APPID",appid).replace("SECRET",secret).replace("CODE",code) ;
        String json = HttpUtils.doGet(url);
        // 字符串转化为json对象
        JSONObject jsonObject = JSONObject.parseObject(json);
        // 根据key值拿到value
        return !StringUtils.isEmpty(jsonObject.getString("openid"))?jsonObject.getString("openid"):
                jsonObject.getString("errmsg");

    }

    @Override
    public String getXcxUrl() {
        String accessToken = this.getAccessToken();
        String url = "https://api.weixin.qq.com/wxa/generate_urllink?access_token=" + accessToken;
        JSONObject object = new JSONObject();

        String res = HttpUtils.doPost(url, object);
        String url_link = JSONObject.parseObject(res).getString("url_link");
        return url_link;

    }


}
